package cn.wei.reallyEnjoy.home.fragment;

import static android.content.ContentValues.TAG;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import cn.wei.reallyEnjoy.R;
import cn.wei.reallyEnjoy.base.BaseFragment;
import cn.wei.reallyEnjoy.home.activity.SearchDiaryActivity;
import cn.wei.reallyEnjoy.home.adapter.HomeFragmentAdapter;
import cn.wei.reallyEnjoy.home.bean.IndexBean;
import cn.wei.reallyEnjoy.utils.Constants;
import okhttp3.Call;

/**
 * 主页面的fragment
 */
public class HomeFragment extends BaseFragment {
    private RecyclerView rv_home;
    private ImageView ib_top;
    private EditText et_search_home;
    private TextView tv_search_btn_home;
    private HomeFragmentAdapter adapter;
    SwipeRefreshLayout swipeRefreshView;

    /**
     * 返回的数据
     */
    private IndexBean indexBean;

    @Override
    public View initView() {
        Log.e(null,"主页面的fragment的UI被初始化");
        View view  = View.inflate(mContext, R.layout.fragment_home,null);
        rv_home = view.findViewById(R.id.rv_home);
        ib_top = view.findViewById(R.id.ib_top);
        et_search_home = view.findViewById(R.id.et_search_home);
        tv_search_btn_home = view.findViewById(R.id.tv_search_btn_home);

        swipeRefreshView = view.findViewById(R.id.refresh);
        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        swipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        swipeRefreshView.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);


        //设置监听事件
        initListener();
        return view;
    }
    @Override
    public void initData() {
        Log.e(null,"主页面的fragment数据的UI被初始化");
        super.initData();
        //联网网络请求的数据
        getDataFromNet();



    }

    private void initListener() {
        //返回顶部监听
        ib_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回到顶部
                rv_home.scrollToPosition(0);
                Toast.makeText(mContext,"回到顶部",Toast.LENGTH_SHORT).show();
            }
        });

        //搜索按钮监听
        tv_search_btn_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(mContext,"点击了搜索按钮",Toast.LENGTH_SHORT).show();
                String keyWord = et_search_home.getText().toString().trim();
                Log.e("Home",keyWord);
                if (TextUtils.equals(keyWord,"")){
                    Toast.makeText(mContext,"请输入搜索内容",Toast.LENGTH_SHORT).show();
                    return;
                }

                Intent intent = new Intent(mContext, SearchDiaryActivity.class);
                intent.putExtra("keyWord",keyWord);
                startActivity(intent);
            }
        });
        //下拉刷新监听
        initRefresh();


    }

    private  void initRefresh(){
        //设置颜色变化过程
        swipeRefreshView.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_green_light,android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        //设置滑动多少距离进行才能刷新
        swipeRefreshView.setDistanceToTriggerSync(150);
        //设置刷新图标大小
        swipeRefreshView.setSize(SwipeRefreshLayout.LARGE);
        //设置刷新时的监听事件
        swipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            //刷新时进行的方法
            //下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
            public void onRefresh() {
                /**
                 * Handler：是一个消息分发对象，进行发送和处理消息，并且其 Runnable 对象与一个线程的 MessageQueue 关联。
                 *
                 * 作用：调度消息，将一个任务切换到某个指定的线程中去执行。
                 */
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getDataFromNet();
                        Toast.makeText(mContext, "刷新成功", Toast.LENGTH_SHORT).show();
                        //停止刷新
                        swipeRefreshView.setRefreshing(false);
                    }
                },1000);
            }
        });
    }


    private void getDataFromNet() {
        String url = Constants.HOME_URL_INDEX;
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new StringCallback()
                {
                    /**
                     * 请求失败回调
                     * @param call
                     * @param e
                     * @param id
                     */

                    @Override
                    public void onError(Call call, Exception e, int id) {

                        Log.e(null,"首页请求失败"+e.getMessage());
                    }

                    /**
                     * 联网成功回调
                     * @param response
                     * @param id
                     */

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(null,"请求成功");
                        //解析数据
                        processData(response);
                    }
                });
    }

    //解析数据
    private void processData(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String data =String.valueOf(jsonObject.get("data"));
        if (data!=null){
            //有数据
            indexBean = JSON.parseObject(data, IndexBean.class);
            //设置适配器
            adapter =  new HomeFragmentAdapter(mContext,indexBean);
            rv_home.setAdapter(adapter);

            GridLayoutManager manager = new GridLayoutManager(getActivity(), 1);

            //设置滑动到哪个位置了的监听
            manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position <= 0) {
                        ib_top.setVisibility(View.GONE);
                    } else {
                        ib_top.setVisibility(View.VISIBLE);
                    }
                    return 1;
                }
            });
            //设置布局管理者
            rv_home.setLayoutManager(manager);

        }else{
            //没有数据
            Toast.makeText(mContext, "暂无数据", Toast.LENGTH_LONG).show();

        }
        Log.e(TAG,"解析成功："+indexBean.getDiaryIndexList().get(0).getTitle());



    }
}
